<?php
/**
 * 定时任务脚本
 */
namespace app\api\controller;
use app\common\controller\Api;
class Crontab extends Api
{
	protected $noNeedLogin = ['*'];
	protected $noNeedRight = ['*'];
	/**
	 * 订单取消
	 */
	public function cancelOrder()
	{
		//获取可取消订单
		//获取15分钟前时间
		$time = strtotime("-15 minutes", time());
		//查询可取消的订单
		$where = [
			'state' => 1,
			'createtime' => ['<', $time],
			'data_type' => 'merchant'
		];
		$list_data = model('app\api\model\wanlshop\Order')->where($where)->select();
		$list_data = collection($list_data)->toArray();
		// 状态
		$sucs = 0;
		$fail = 0;
		if(!empty($list_data))
		{
			foreach($list_data as $key => $value)
			{
				$row = model('app\api\model\wanlshop\Order')->get(['id' => $value['id']]);
				$result = $row->allowField(true)->save(['state' => 7]);
				if($result)
				{	
					// 还原优惠券 1.0.2升级
					if($row['coupon_id'] != 0){
						model('app\api\model\wanlshop\CouponReceive')->where(['id' => $row['coupon_id'], 'user_id' => $row['user_id']])->update(['state' => 1]);
	                }
	                // 释放库存 1.0.3升级
	                foreach(model('app\api\model\wanlshop\OrderGoods')->all(['order_id' => $row['id']]) as $vo){
	                	// 查询商品是否需要释放库存
	                	if(model('app\api\model\wanlshop\Goods')->get($vo['goods_id'])['stock'] == 'porder'){
	                		model('app\api\model\wanlshop\GoodsSku')->where('id', $vo['goods_sku_id'])->setInc('stock', $vo['number']);
	                	}
	                }
	                $sucs++;
	            }else
	            {
	            	$fail++;
	            }
			}
		}
		$this->success('ok', ['sucs' => $sucs, 'fail' => $fail]);
	}

	/**
	 * 订单收货
	 */
	public function confirmOrder()
	{
		//获取可收货订单
		//获取7天前时间
		$time = strtotime("-7 days", time());
		$where = [
			'state' => 3,
			'delivertime' => ['<', $time],
			'data_type' => 'merchant'
		];
		$list_data = model('app\api\model\wanlshop\Order')->where($where)->select();
		$list_data = collection($list_data)->toArray();
		// 状态
		$sucs = 0;
		$fail = 0;
		if(!empty($list_data))
		{
			foreach($list_data as $key => $value)
			{
				$order = model('app\api\model\wanlshop\Order')->where(['id' => $value['id'], 'state'=> 3])->find();
				// 获取支付 1.1.2升级
				$pay = model('app\api\model\wanlshop\Pay')->get(['order_id' => $value['id'], 'type' => 'goods']);
                // 查询是否有退款
                $refund = model('app\api\model\wanlshop\Refund')->where(['order_id' => $value['id'], 'state' => 4, 'order_type' => 'goods'])->select();
                // 退款存在
                if($refund){
                	$fail++;
                	continue;
                }
                // 更新订单状态
                $order->save(['state' => 6,'taketime' => time()],['id' => $value['id']]);
                $sucs++;
			}
		}
		$this->success('ok', ['sucs' => $sucs, 'fail' => $fail]);
	}
}